package com.juno.cafeNoa.admin;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.juno.cafeNoa.admin.util.Util;

public class GCMIntentService extends GCMBaseIntentService {
	private static final String tag = "GCMIntentService";
	public static final String PROJECT_ID = "583693922537";

	public GCMIntentService() {
		this(PROJECT_ID);
	}

	public GCMIntentService(String project_id) {
		super(project_id);
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		String content = intent.getStringExtra("ORDER_CONTENT");
		String phone = intent.getStringExtra("USER_PHONE");
		String number = intent.getStringExtra("ORDER_NUMBER");

		Intent actionIntent = new Intent(context, ItemDetailFragment.class);
		actionIntent.putExtra("ORDER_COME", true);
		PendingIntent pendingintent = PendingIntent.getActivity(context, 0,
				actionIntent, PendingIntent.FLAG_ONE_SHOT);
		Util.acquireCpuWakeLock(context);

		// R.drawable.ic_launcher는 임시적으로 이미지 적용.
		showNotification(context, R.drawable.ic_launcher, number + "번 주문 도착 !",
				content + " , 전화번호 : " + phone, pendingintent, 0);
	}

	@Override
	protected void onError(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		Log.d(tag, "on_error. errorId : " + arg1);
	}

	@Override
	protected void onRegistered(Context context, String regId) {
		Log.d(tag, "onRegistered. regId : " + regId);
	}

	@Override
	protected void onUnregistered(Context context, String regId) {
		Log.d(tag, "onUnregistered. regId : " + regId);
	}

	/**
	 * showNotification : Notification을 띄우기 위한 메소드.<br>
	 * 
	 * @author JunHo
	 */
	private void showNotification(Context context, int notifyImgResId,
			CharSequence title, CharSequence text,
			PendingIntent intentActivity, int notifyId) {
		Notification notification = new NotificationCompat.Builder(context)
				.setContentTitle(title).setTicker(text).setContentText(text)
				.setSmallIcon(notifyImgResId)
				.setDefaults(Notification.DEFAULT_ALL).setAutoCancel(true)
				.addAction(notifyImgResId, "Action", intentActivity).build();
		notification.setLatestEventInfo(context, title, text, intentActivity);

		NotificationManager mNM = (NotificationManager) context
				.getSystemService(context.NOTIFICATION_SERVICE);
		mNM.notify(notifyId, notification);

		try {
			// 3초간 정지후 cpulock을 해제함.
			Thread.sleep(1000 * 5);
			Util.releaseCpuLock();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
